package com.kaishengit.test;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;
import org.apache.poi.ss.usermodel.CellStyle;

public class ExcelUtils {
  //生成Excel表头
 public static void exportHeaders(HSSFWorkbook workbook,HSSFSheet sheet,String headers){
  /*表头行以；分割
   *表头项目以：分割 
   *表头项目项以，分割 
   */
  //设置单元格样式
  CellStyle style=workbook.createCellStyle();
  //设置水平居中对齐
  style.setAlignment((short)(CellStyle.ALIGN_CENTER));
  //设置垂直居中对齐
  style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
  //设置自动换行
  style.setWrapText(true);
  
  String[] Rows=headers.split(";");
  for(int m=0;m<Rows.length;m++){
   HSSFRow hssfRow=sheet.createRow(m);
   String Row=Rows[m];
   String[] HeadItems=Row.split(":");
   for(int n=0;n<HeadItems.length;n++){
    String HeadItem=HeadItems[n];
    String[] Items=HeadItem.split(",");
    short fromRow=(short)m;
    short fromCol=(short)(Short.parseShort(Items[0])-1);
    String headContent;
    if(Items.length==4){
     short toRow=(short)(Short.parseShort(Items[1])-1);
     short toCol=(short)(Short.parseShort(Items[2])-1);
     headContent=Items[3];
     Region region=new Region(fromRow,fromCol,toRow,toCol);
     sheet.addMergedRegion(region);
    }else{
     headContent=Items[1];
    }
    HSSFCell cell=hssfRow.createCell(fromCol);
    cell.setCellValue(headContent);
    cell.setCellStyle(style);
   }
  }
 }
 
 public static void exportRow(HSSFSheet sheet,int rowIndex,String[] datas){
  HSSFRow row=sheet.createRow(rowIndex);
  for(int i=0;i<datas.length;i++){
   HSSFCell cell=row.createCell(i);
   cell.setCellValue(datas[i]);
  }
 }
}